package com.study.talk.ui.adapter.moment

import android.annotation.SuppressLint
import android.graphics.Insets
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.view.WindowInsets
import android.widget.EditText
import android.widget.PopupMenu
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.internal.ViewUtils.hideKeyboard
import com.study.common.GSONUtil
import com.study.common.ToastUtil
import com.study.talk.R
import com.study.talk.App
import com.study.talk.databinding.MomentsItemBinding
import com.study.talk.data.model.MomentLike
import com.study.talk.data.model.resp.MomentResponse
import com.study.talk.data.model.vo.MomentCommentVo
import com.study.talk.data.model.vo.MomentLikeVo
import com.study.talk.data.repository.MomentRepository
import com.study.talk.utils.extras.take
import com.study.talk.utils.extras.useless
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


/** 定义MomentListAdapter类 用于显示动态列表  */
class MomentsAdapter(
    private val app : App, private val momentRepository: MomentRepository
) : ListAdapter<MomentResponse, MomentsAdapter.ViewHolder>(DiffCallBack()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            DataBindingUtil.inflate(
                LayoutInflater.from(parent.context), R.layout.moments_item, parent, false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        // 获取当前位置的动态对象
        val moment = getItem(holder.adapterPosition)
        holder.bind(moment)
        // 设置动态操作按钮的点击事件
        holder.binding.momentListViewItemAction.setOnClickListener { v: View ->
            // 初始化菜单操作
            showMenuAction(holder, v)
        }
    }

    override fun onBindViewHolder(
        holder: ViewHolder, position: Int, payloads: MutableList<Any>
    ) {
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position)
        } else {
            for (payload in payloads) {
                when (payload as String) {
                    "comment" -> holder.vm.changeComments(getItem(holder.adapterPosition).momentComments)
                    "likes" -> holder.vm.changeLikes(getItem(holder.adapterPosition).momentLikes)
                    "likeState" -> holder.vm.changeLikeState(getItem(holder.adapterPosition).myLikeState)
                }
            }
        }
    }

    /** 初始化菜单操作  */
    @SuppressLint("InflateParams", "RestrictedApi")
    private fun showMenuAction(holder: ViewHolder, v: View) {
        // 创建弹出菜单
        val popupMenu = PopupMenu(v.context, v)
        popupMenu.menuInflater.inflate(R.menu.moment_action_menu, popupMenu.menu)
        // 根据点赞状态设置菜单标题
        if (holder.vm.myLikeState.value == 1) popupMenu.menu.getItem(0).setTitle("取消点赞")
        popupMenu.show()
        // 设置菜单项的点击事件
        popupMenu.setOnMenuItemClickListener { item: MenuItem ->
            when (item.itemId) {
                R.id.moment_action_like -> {
                    val requestBody = MomentLikeVo(
                        holder.vm.moment.id,
                        app.localUserId,
                        app.username,
                        if (holder.vm.myLikeState.value == 0) 1 else 0
                    )
                    CoroutineScope(Dispatchers.IO).launch {
                        momentRepository.updateMomentLike(momentLikeVo = requestBody,
                            success = { state ->
                                holder.vm.changeLikeState(state)
                                //更新显示数据
                            },
                            fail = { msg: String ->
                                ToastUtil.showToast(holder.binding.root.context, msg)
                            })
                        momentRepository.getLikeList(holder.vm.moment.id, success = { likes ->
                            holder.vm.changeLikes(likes)
                        }, fail = { msg ->
                            ToastUtil.showToast(holder.binding.root.context, msg)
                        })
                    }
                }

                R.id.moment_action_comment -> {
                    // 显示底部评论对话框
                    val bottomSheetDialog = BottomSheetDialog(v.context)
                    val contentView =
                        LayoutInflater.from(v.context).inflate(R.layout.comment_bottom_view, null)
                    contentView.fitsSystemWindows = false
                    contentView.setOnApplyWindowInsetsListener { v, insets ->
                        // 获取软键盘插入区域
                        val imeInsets: Insets = insets.getInsets(WindowInsets.Type.ime())
                        val navigationBarInsets =
                            insets.getInsets(WindowInsets.Type.navigationBars())
                        // 设置底部填充，防止键盘遮挡
                        if (imeInsets.bottom == 0) {
                            v.setPadding(0, 0, 0, 0)
                        } else {
                            v.setPadding(0, 0, 0, imeInsets.bottom - navigationBarInsets.bottom)
                        }
                        insets
                    }
                    bottomSheetDialog.setContentView(contentView)
                    contentView.findViewById<TextView>(R.id.moment_list_comment_msg_send_bt)
                        .setOnClickListener {
                            val commentEdit =
                                contentView.findViewById<EditText>(R.id.moment_list_comment_msg_edit)
                            if (commentEdit.useless("不能评论空内容")) return@setOnClickListener
                            // 添加评论
                            val requestBody = MomentCommentVo(
                                holder.vm.moment.id,
                                app.localUserId,
                                app.username,
                                commentEdit.take(), // 获取输入的评论内容并清除评论
                            )
                            CoroutineScope(Dispatchers.IO).launch {
                                momentRepository.addComment(requestBody, success = {
                                    // 获取好友动态列表并更新数据
                                    holder.vm.changeComments(it)
                                    launch(Dispatchers.Main) {
                                        //隐藏键盘
                                        hideKeyboard(contentView)
                                        bottomSheetDialog.dismiss()
                                    }
                                }, fail = { msg ->
                                    ToastUtil.showToast(v.context, msg)
                                    launch(Dispatchers.Main) {
                                        bottomSheetDialog.dismiss()
                                    }
                                })
                            }
                            /* NetApi.addMomentComment(app.user,
                                 holder.vm.moment.id,
                                 commentEdit.take(), // 获取输入的评论内容并清除评论
                                 success = {
                                     // 获取好友动态列表并更新数据
                                     holder.vm.changeComments(it)
                                     AppExecutor.mainHandler().post {
                                         //隐藏键盘
                                         hideKeyboard(contentView)
                                         bottomSheetDialog.dismiss()
                                     }
                                 },
                                 fail = { msg ->
                                     ToastUtil.showToast(v.context, msg)
                                     AppExecutor.mainHandler().post {
                                         bottomSheetDialog.dismiss()
                                     }
                                 })*/
                        }
                    bottomSheetDialog.show()
                }
            }
            true
        }
    }


    inner class ViewHolder(val binding: MomentsItemBinding) :
        RecyclerView.ViewHolder(binding.root) {

        lateinit var vm: MomentItemViewModel
        private lateinit var commentsAdapter: MomentCommentsAdapter


        fun bind(moment: MomentResponse) {
            vm = ViewModelProvider(
                object : ViewModelStoreOwner {
                    override val viewModelStore: ViewModelStore
                        get() = ViewModelStore()
                }, MomentItemViewModel.Factory(moment)
            )[MomentItemViewModel::class]
            binding.vm = vm
            vm.photos.observe(binding.root.context as LifecycleOwner) { photos ->
                initPhotoView(photos, binding)
            }

            vm.likes.observe(binding.root.context as LifecycleOwner) { likes ->
                showLikeView(likes, binding)
            }
            vm.comments.observe(binding.root.context as LifecycleOwner) { comments ->
                commentsAdapter.submitList(comments)
            }

            binding.momentListViewItemCommentListView.layoutManager =
                LinearLayoutManager(binding.root.context)
            commentsAdapter =
                MomentCommentsAdapter(moment.userId == app.localUserId, app.localUserId, momentRepository)
            binding.momentListViewItemCommentListView.adapter = commentsAdapter
            commentsAdapter.submitList(vm.comments.value)
        }

        /** 初始化图片视图  */
        private fun initPhotoView(photos: List<String>, binding: MomentsItemBinding) {
            // 检查是否有图片，如果没有则隐藏图片网格
            if (photos.isEmpty()) {
                binding.momentListViewItemGridview.visibility = View.GONE
            } else {
                // 根据图片数量设置网格列数
                val gridLayoutManager = GridLayoutManager(binding.root.context, 3)
                when (photos.size) {
                    1 -> gridLayoutManager.spanCount = 1
                    2, 3, 4 -> gridLayoutManager.spanCount = 2
                    5, 6, 7, 8, 9 -> gridLayoutManager.spanCount = 3
                }
                binding.momentListViewItemGridview.layoutManager = gridLayoutManager

                val adapter = ImageGridAdapter()

                // 设置图片网格的适配器
                binding.momentListViewItemGridview.adapter = adapter
                adapter.submitList(photos)
            }
        }

        /** 初始化点赞视图  */
        private fun showLikeView(likes: List<MomentLike>, binding: MomentsItemBinding) {
            // 检查是否有点赞，如果没有则隐藏点赞布局
            if (likes.isEmpty()) {
                binding.momentListViewItemLikeLayout.visibility = View.GONE
            } else {
                // 构建点赞用户名称字符串
                val sb = StringBuilder("")
                likes.forEach {
                    if (it.likeState == 1) {
                        if (sb.toString().isNotEmpty()) {
                            sb.append(",${it.userName}")
                        } else {
                            sb.append(it.userName)
                        }
                    }
                }
                // 如果没有点赞用户则隐藏点赞布局
                if (sb.toString().isEmpty()) {
                    binding.momentListViewItemLikeLayout.visibility = View.GONE
                } else {
                    // 显示点赞布局并设置点赞用户名称
                    binding.momentListViewItemLikeLayout.visibility = View.VISIBLE
                    binding.momentListViewItemLikeText.text = sb.toString()
                }
            }
        }
    }

    class DiffCallBack : DiffUtil.ItemCallback<MomentResponse>() {
        override fun areItemsTheSame(oldItem: MomentResponse, newItem: MomentResponse): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: MomentResponse, newItem: MomentResponse): Boolean {
            return GSONUtil.toJson(oldItem) == GSONUtil.toJson(newItem)
        }

        override fun getChangePayload(oldItem: MomentResponse, newItem: MomentResponse): Any? {
            if (oldItem.myLikeState != newItem.myLikeState) return "likeState"
            if (oldItem.momentLikes.size != newItem.momentLikes.size) return "likes"
            if (oldItem.momentComments.size != newItem.momentComments.size) return "comment"
            return super.getChangePayload(oldItem, newItem)
        }
    }
}
